package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class sishuzhihe {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        if(nums==null||nums.length<4){
            return null;
        }
        List<List<Integer>> list=new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-3;){
            int a=nums[i];
            for(int j=i+1;j<nums.length-2;){
                int b=nums[j];
                int left=j+1;
                int right=nums.length-1;
                while(left<right){
                    if(nums[left]+nums[right]<target-a-b){
                        left++;
                    }else if(nums[left]+nums[right]>target-a-b){
                        right--;
                    }else{
                        list.add(Arrays.asList(a,b,nums[left],nums[right]));
                        left++;
                        right--;
                        while(left<right&&nums[left]==nums[left-1]){
                            left++;
                        }
                        while(left<right&&nums[right]==nums[right+1]){
                            right--;
                        }
                    }
                }
                j++;
                while(j<nums.length-2&&nums[j]==nums[j-1]){
                    j++;
                }

            }
            i++;
            while(i<nums.length-3&&nums[i]==nums[i-1]){
                i++;
            }



        }
        return list;

    }

    public static void main(String[] args) {
        int[] nums={1,0,-1,0,-2,2};
        List<List<Integer>> listList = fourSum(nums, 0);
        System.out.println(listList);


    }
}
